import { fileURLToPath, URL } from 'node:url'

import { defineConfig, loadEnv } from 'vite'
import vue from '@vitejs/plugin-vue'
import vueDevTools from 'vite-plugin-vue-devtools'

// https://vite.dev/config/
export default defineConfig(({ mode }) => {
    // 加载环境变量
    const env = loadEnv(mode, process.cwd(), '')

    return {
        plugins: [vue(), vueDevTools()],
        optimizeDeps: {
            include: ['pdfjs-dist'],
        },
        resolve: {
            alias: {
                '@': fileURLToPath(new URL('./src', import.meta.url)),
            },
        },
        server: {
            proxy: {
                '/api': {
                    target: env.VITE_BASE_URL,
                    changeOrigin: true,
                    rewrite: path => path.replace(/^\/api/, ''),
                },
            },
        },
        build: {
            outDir: 'frontend', // 直接输出到 frontend 目录
            assetsDir: 'assets', // 静态资源存放目录
            emptyOutDir: true, // 构建前清空目录
            rollupOptions: {
                output: {
                    assetFileNames: assetInfo => {
                        const fileName = assetInfo.names?.[0] || 'unknown'
                        const extType = fileName.split('.').pop()?.toLowerCase() || 'misc'

                        if (['png', 'jpg', 'jpeg', 'svg', 'gif', 'ico'].includes(extType)) {
                            return 'assets/img/[name]-[hash][extname]'
                        } else if (['mp4', 'webm', 'ogg', 'mov'].includes(extType)) {
                            return 'assets/video/[name]-[hash][extname]'
                        } else if (extType === 'css') {
                            return 'assets/css/[name]-[hash][extname]'
                        } else {
                            return 'assets/misc/[name]-[hash][extname]'
                        }
                    },
                    chunkFileNames: 'assets/js/[name]-[hash].js',
                    entryFileNames: 'assets/js/[name]-[hash].js',
                },
                input: {
                    main: './index.html', // 显式指定入口文件路径（可选）
                },
            },
        },
    }
})
